import { app, BrowserWindow,ipcMain } from 'electron';
import path from 'node:path';
import started from 'electron-squirrel-startup';
import SocketServer from "./websocket/server";
import { AppDataSource } from './data-source';
import { User } from './entity/user';
import {StringUtils} from "./util/string_utils";
// 创建 WebSocket 服务实例
const wsServer = new SocketServer(8765);
if (started) {
  app.quit();
}
const handlers = {
  query : async (data:any): Promise<any> => {
    console.log(data.message+'==============='); // 接收到渲染进程的数据
    return {message:'您的问候已收到，这是我的回复'};
  },
  login: async (data:any): Promise<any> => {
    const username:string = data.username;
    const password:string = data.password;
    const user = await AppDataSource.manager.findOneBy(User, {login_id:username});
    if(user){
      const password_hash = StringUtils.secureHash(password);
      if(StringUtils.verifyPassword(password, password_hash)){
        return {message:'登录成功',success:true,data:{token:password_hash}};
      }
    }
    return {message:'用户不存在或密码错误',success:false};
  }
}
const createWindow = async () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    autoHideMenuBar: true, // 按 `Alt` 键可临时显示菜单栏
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });
  console.log(MAIN_WINDOW_VITE_DEV_SERVER_URL)
  // and load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
  }
  // 启动 WebSocket 服务
  wsServer.start();
  await AppDataSource.initialize();
  console.log('Database initialized');
  // 添加连接处理器 - 通知渲染进程
  wsServer.addConnectionHandler(() => {
    if (mainWindow) {
      mainWindow.webContents.send('connection-update', {
        type: 'connection',
        count: wsServer.getClientCount()
      });
    }
  });

  // 添加断开连接处理器
  wsServer.addDisconnectionHandler(() => {
    if (mainWindow) {
      mainWindow.webContents.send('connection-update', {
        type: 'disconnection',
        count: wsServer.getClientCount()
      });
    }
  });
  // 添加消息处理器 - 转发到渲染进程
  wsServer.addMessageHandler((message) => {
    if (mainWindow) {
      mainWindow.webContents.send('python-message', message);
    }
  });
  ipcMain.handle('fromSon', async (event, { type, data }) => {
    if('resize-window'===type){
      mainWindow.setSize(data.width, data.height);
      // 如果需要居中
      mainWindow.center();
      return ;
    }
    if (handlers[type]) {
      console.log('<UNK>', type, data);
      return handlers[type](data);
    } else {
      throw new Error(`No handler for type: ${type}`);
    }
  });
  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
// 应用关闭时清理
app.on('before-quit', () => {
  wsServer.stop();
});
app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
